<?php
/*
Plugin Name: odNewsletterWpPlugin
Plugin URI: http://ondrejd.info/projects/wordpress-plugins/
Description: Simple newsletter plugin created without interaction with WordPress users.
Version: ##VERSION##
Author: Ondrej Donek
Author URI: http://www.ondrejd.info/
*/

/*  ***** BEGIN LICENSE BLOCK *****
    Version: MPL 1.1
    
    The contents of this file are subject to the Mozilla Public License Version 
    1.1 (the "License"); you may not use this file except in compliance with 
    the License. You may obtain a copy of the License at 
    http://www.mozilla.org/MPL/
    
    Software distributed under the License is distributed on an "AS IS" basis,
    WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
    for the specific language governing rights and limitations under the
    License.
    
    The Original Code is WordPress Newsletter Plugin.
    
    The Initial Developer of the Original Code is
    Ondrej Donek.
    Portions created by the Initial Developer are Copyright (C) 2010
    the Initial Developer. All Rights Reserved.
    
    Contributor(s):
    
    ***** END LICENSE BLOCK ***** */

require_once realpath(dirname(__FiLE__) . '/odWpPlugin.php');


#{{{ odNewsletterWpPlugin_Models_Newsletter ---
if(!class_exists('odNewsletterWpPlugin_Models_Newsletter')):
#!src_models_Newsletter##
endif;
#}}} --- odNewsletterWpPlugin_Models_Newsletter


#{{{ odNewsletterWpPlugin_Tables_Newsletter ---
if(!class_exists('odNewsletterWpPlugin_Tables_Newsletter')):
#!src_tables_Newsletter##
endif;
#}}} --- odNewsletterWpPlugin_Tables_Newsletter


#{{{ odNewsletterWpPlugin_Forms_Newsletter ---
if(!class_exists('odNewsletterWpPlugin_Forms_Newsletter')):
#!src_forms_Newsletter##
endif;
#}}} --- odNewsletterWpPlugin_Forms_Newsletter


#{{{ odNewsletterWpPlugin ---
if(!class_exists('odNewsletterWpPlugin')):

/**
 * Main catalog object
 * 
 * @author Ondrej Donek, <ondrejd@gmail.com>
 * @category odNewsletterWpPlugin
 * @version ##VERSION##
 */
class odNewsletterWpPlugin extends odWpPlugin
{
	/**
	 * Constructor.
	 *
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct(
			'od-newsletter-wpplugin',
			'odNewsletterWpPlugin',
			'##VERSION##', 
			array(
				'hasAdmin' => true,
				'adminConfig' => array(
					'stylesheet' => true
				),
				'hasLocales' => true,
				'hasOptions' => true, 
				'defaultOptions' => array(
					'default_recipients' => ''
				)
			)
		);
		
		// Activation/deactivation
		register_activation_hook(__FILE__, array(&$this, 'activate'));
		register_deactivation_hook(__FILE__, array(&$this, 'deactivate'));
		
		// Ensure that plugin's options are initialized
		$options = $this->initOptions();
		
		if(is_admin()) {
			// Register admin menu
			add_action('admin_menu', array(&$this, 'adminMenu'));
		}
		else {
      // Register content filter
      //add_filter('the_content', array(&$this, 'contentFilter'));
      
      // Initialize plugin's widgets
      //register_widget('...');
    }
	} // end __construct()
	
	/**
	 * Activates the plugin
	 * 
	 * @returns void
	 */
	public function activate()
	{
    // Collect plugins metric data
		$this->collectMetricsData($this->mId, self::VERSION, get_bloginfo('home'), 'activate');
		
		// Ensure that database tables are created
		$newsletterModel = new odNewsletterWpPlugin_Models_Newsletter();
		$newsletterModel->createTable();
	} // end activate()

	/**
	 * Deactivates the plugin
	 * 
	 * @returns void
	 */
	public function deactivate()
	{
		// Collect plugins metric data
		$this->collectMetricsData($this->mId, self::VERSION, get_bloginfo('home'), 'deactivate');
		
		// TODO Destroy database if user want it! 
	} // end deactivate()
	
	/**
	 * Registers administration menu for the plugin
	 * 
	 * @returns void
	 */
	public function adminMenu() 
	{
		add_menu_page(
				__('Newsletter', $this->mId),
				__('Newsletter', $this->mId),
				0,
				$this->mId,
				array(&$this, 'adminMainPage'),
				WP_PLUGIN_URL . '/' . $this->mId . '/resources/icon16.png'
		);
		add_submenu_page(
				$this->mId,
				__('Newsletter - Vytvoř nový', $this->mId),
				__('Vytvoř nový', $this->mId),
				0,
				$this->mId . '-add_newsletter',
				array(&$this, 'adminAddNewsletter')
		);
		add_submenu_page(
				$this->mId,
				__('Newsletter - Nastavení', $this->mId),
				__('Nastavení', $this->mId),
				0,
				$this->mId . '-settings',
				array(&$this, 'adminSettingsPage')
		);
	}
	
	/**
	 * Renders main admin page of the plugin.
	 * 
	 * @returns void
	 */
	public function adminMainPage()
	{
		$title = __('Newsletter', $this->mId);
		$icon  = WP_PLUGIN_URL . '/' . $this->mId . '/resources/icon32.png';
		$url = get_bloginfo('home') . '/wp-admin/admin.php?page=' . $this->mId;
		$url1 = get_bloginfo('home') . '/wp-admin/admin.php?page=' . $this->mId . '-newsletter';
		$table = new odNewsletterWpPlugin_Tables_Newsletter();
    $output = '';
    
    if(array_key_exists('delete', $_GET)) {
      // Delete selected item
      $output .= '<form action="' . $url . '" method="POST" class="delete-form"><div>';
      $output .= '<input type="hidden" name="item_ID" value="' . $_GET['delete'] . '"/>';
      $output .= '<strong>Skutečně chcete vymazat položku s ID <code>' . $_GET['delete'] . '</code>?</strong> ';
      $output .= '<input type="submit" value="' . __('Ne', $this->mId) . '" class="button-secondary action"/> ';
      $output .= '<input type="submit" name="delete_confirmed" value="' . __('Ano', $this->mId) . '" class="button-primary action"/>';
      $output .= '</div></form>' . PHP_EOL;
    }
    else if(array_key_exists('delete_confirmed', $_POST)) {
      $item_ID = (int) $_POST['item_ID'];
      $model = new odNewsletterWpPlugin_Models_Newsletter();
      $model->remove('`ID` = ' . $item_ID);
      
      $output .= '<div class="success"><p>Položka s ID <code>' . $item_ID . '</code> byla úspěšně vymazána.</p></div>' . PHP_EOL;
    }
    else if(array_key_exists('send_item', $_GET)) {
      // Send selected item
      $model = new odNewsletterWpPlugin_Models_Newsletter();
      $res = $model->get('`t1`.`ID` = ' . (int) $_GET['send_item']);
      
      if(count($res) == 1) {
        if($this->_sendNewsletter($res[0])) {
          $output .= '<div class="success"><p>Newsletter byl úspěšně odeslán všem příjemcům.</p></div>' . PHP_EOL;
        } else {
          $output .= '<div class="error"><p>Newsletter nebyl úspěšně odeslán!</p></div>' . PHP_EOL;
        }
      } else {
        $output .= '<div class="error"><p>Newsletter nebyl dle daného ID nalezen - Nedošlo k odeslání emailů!</p></div>' . PHP_EOL;
      }
    }
    
    $output .= $table->render();
    
		$this->mAdminRenderer->adminPage($title, $output, $icon);
	}
	
	/**
	 * Renders page with reservation select for the choosen date. 
	 * Called from `adminMainPage`.
	 * 
	 * @return void
	 */
	public function adminAddNewsletter()
	{
		$title = __('Newsletter - Vytvoř nový', $this->mId);
		$url   = get_bloginfo('home') . '/wp-admin/admin.php?page=' . $this->mId . '-add_newsletter';
		$icon  = WP_PLUGIN_URL . '/' . $this->mId . '/resources/icon32.png';
		$form = new odNewsletterWpPlugin_Forms_Newsletter();
		$form->setValue('op', 'add');
    $options = $this->getOptions();
    $description = '';
    
    $form->setValue('recipients', $options['default_recipients']);
		
    if(array_key_exists('item_ID', $_GET)) {
      $item_ID = (int) $_GET['item_ID'];
      $model = new odNewsletterWpPlugin_Models_Newsletter();
      $newsletter = $model->get('`t1`.`ID` = ' . $item_ID . ' ');
      
      if(count($newsletter) == 1) {
        $newsletter[0]['html_body'] = $newsletter[0]['html_body'];
        $form->setValues($newsletter[0]);
        
        if(array_key_exists('create_new_from', $_GET)) {
          $form->setValue('op', 'add');
        } else {
          $title = __('Newsletter - Edituj položku #' . $item_ID, $this->mId);
          $form->setValue('op', 'edit');
        }
        
      } else {
        $form->setDescription(__('Položku s daným ID se nepodařilo v databázi nalézt!'), $this->mId);
      }
    }
    
    if(array_key_exists('op', $_POST)) {
      $model = new odNewsletterWpPlugin_Models_Newsletter();
      
      if($_POST['op'] == 'add') {
        $values = array(
          'subject' => $_POST['subject'], 
          'recipients' => $_POST['recipients'], 
          'text_body' => $_POST['text_body'],
          'html_body' => str_replace("'", "`", htmlentities($_POST['html_body']))
        );
        
        $send_immediately = (array_key_exists('send_immediately', $_POST))
            ? ((strtolower($_POST['send_immediately']) == 'on') ? true : false)
            : false;
        if($send_immediately === true) {
          $values['sent'] = 1;
          $values['sent_when'] = date('Y-m-d H:i:s');
          
          if($this->_sendNewsletter($values)) {
            $description .= 'Newsletter byl úspěšně odeslán všem příjemcům. ';
          } else {
            $description .= 'Newsletter nebyl úspěšně odeslán! ';
          }
        }
        
        $model->insert($values);
        $description .= 'Nová položka byla úspěšně vytvořena.';
        $form->setDescription($description);
      } else {
        $values = array(
          'subject' => $_POST['subject'], 
          'recipients' => $_POST['recipients'], 
          'text_body' => $_POST['text_body'],
          'html_body' => str_replace("'", "`", htmlentities($_POST['html_body']))
        );
        
        $send_immediately = (array_key_exists('send_immediately', $_POST))
            ? ((strtolower($_POST['send_immediately']) == 'on') ? true : false)
            : false;
        if($send_immediately === true) {
          $values['sent'] = 1;
          $values['sent_when'] = date('Y-m-d H:i:s');
          
          if($this->_sendNewsletter($values)) {
            $description .= 'Newsletter byl úspěšně odeslán všem příjemcům.';
          } else {
            $description .= 'Newsletter nebyl úspěšně odeslán!';
          }
        }
        
        $model->update($values, '`ID` = ' . $item_ID);
        $description .= 'Položka byla úspěšně aktualizována.';
      }
    }
    
    $form->setDescription($description);
		$this->mAdminRenderer->adminPage($title, $form->render(), $icon);
	}
	
	/** 
	 * Renders settings page for the plugin
	 * 
	 * @return void
	 */
	public function adminSettingsPage()
	{
		$title = __('Newsletter - Nastavení', $this->mId);
		$icon  = WP_PLUGIN_URL . '/' . $this->mId . '/resources/icon32.png';
		$formUrl = get_bloginfo('home') .'/wp-admin/admin.php?page=' . $this->mId . '-settings';
		$options = $this->getOptions();
		
		if(isset($_POST['settings_save'])) {
			// TODO $options['default_sender'] = $_POST['option-default_sender'];
			// TODO $options['default_replyto'] = $_POST['option-default_replyto'];
			$options['default_recipients'] = $_POST['option-default_recipients'];
			update_option($this->mId . '-options', $options);
			
			$this->mAdminRenderer->adminMsg(__('Nastavení pluginu bylo aktualizováno.', $this->mId));
		}
		
		$content  = '<form action="' . $formUrl . '" method="post" enctype="multipart/form-data">' . PHP_EOL;
		$content .= '	<div>' . PHP_EOL;
		$content .= '		<table class="widefat post fixed" cellpadding="1" cellspacing="1"     style="100%;">' . PHP_EOL;
		$content .= '			<tr>' . PHP_EOL;
		$content .= '				<th scope="row" style="vertical-align: top;"><label for="option-default_recipients">' . __('Defaultní příjemci (vkládejte emailové adresy oddělené středníkem):', $this->mId) . '</label></th>' . PHP_EOL;
		$content .= '				<td><textarea name="option-default_recipients" style="width: 100%;" rows="5">' . $options['default_recipients'] . '</textarea></td>' . PHP_EOL;
		$content .= '			</tr>' . PHP_EOL;
		$content .= '		</table>' . PHP_EOL;
		$content .= '		<input type="submit" value=" ' . __('Uložit', $this->mId) . ' " name="settings_save" class="button-primary action" />' . PHP_EOL;
		$content .= '	</div>' . PHP_EOL;
		$content .= '</form>' . PHP_EOL;
		
		$this->mAdminRenderer->adminPage($title, $content, $icon);
	}
  
  /**
   * Send newsletter to all of recipients.
   * 
   * @param array $aNewsletterId
   * @return boolean
   */
  protected function _sendNewsletter($aNewsletter = null)
  {
		require_once ABSPATH . WPINC . '/class-phpmailer.php';
		require_once ABSPATH . WPINC . '/class-smtp.php';
    $mailer = new PHPMailer();
    
    $mailer->IsHtml(true);
    $mailer->Subject = $aNewsletter['subject'];
    $mailer->From = 'info@akpejchal.cz';
    $mailer->FromName = get_bloginfo('name');
    $mailer->Body = html_entity_decode($aNewsletter['html_body']);
    $mailer->AltBody = $aNewsletter['text_body'];
    
    $recipients = explode(';', $aNewsletter['recipients']);
    foreach($recipients as $recipient) {
      $mailer->AddAddress($recipient);
    }
    
    return $mailer->Send();
  }
	
} // End of odNewsletterWpPlugin

endif;
#}}} --- odNewsletterWpPlugin

if(class_exists('odNewsletterWpPlugin')):
// Initialize plugin
$od_catalog_wpplugin =  new odNewsletterWpPlugin();
endif;
